package io.nads.api.impl;

import cn.hutool.core.codec.Base64;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import io.nads.api.TTS;
import io.nads.utils.HttpRequestUtil;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;

import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.util.*;

/**
 * 七牛云文字转语音(TTS)工具类
 * 使用新的OpenAI兼容API端点和Bearer Token认证
 */
@Data
@Slf4j
public class QiniuTTS implements TTS {
    
    private final String apiKey;
    private final String baseUrl;

    public QiniuTTS(String apiKey, String baseUrl) {
        this.apiKey = apiKey;
        this.baseUrl = baseUrl;
        
        log.info("QiniuTTS初始化成功, baseUrl={}", baseUrl);
    }
    
    /**
     * 发送带Bearer Token认证的GET请求
     * @param url 请求URL
     * @return 响应结果
     */
    private JSONObject getWithBearerToken(String url) {
        return HttpRequestUtil.getWithBearerToken(url, apiKey, "QiniuTTS/1.0", "TTS");
    }
    
    /**
     * 发送带Bearer Token认证的POST请求
     * @param url 请求URL
     * @param data 请求数据
     * @return 响应结果
     */
    private JSONObject postWithBearerToken(String url, Map<String, Object> data) {
        return HttpRequestUtil.postWithBearerToken(url, data, apiKey, "QiniuTTS/1.0", "TTS");
    }

    @Override
    public List<String> getSupportedVoices() {
        String voiceListUrl = baseUrl; // 直接使用配置的URL
        log.info("voiceListUrl: {}", voiceListUrl);
        JSONObject response = getWithBearerToken(voiceListUrl);
        
        List<String> voices = new ArrayList<>();
        if (response != null && response.containsKey("data")) {
            JSONArray voiceArray = response.getJSONArray("data");
            for (int i = 0; i < voiceArray.size(); i++) {
                JSONObject voiceObj = voiceArray.getJSONObject(i);
                String voiceName = voiceObj.getStr("voice_name");
                String voiceType = voiceObj.getStr("voice_type");
                voices.add(voiceType + " (" + voiceName + ")");
            }
        } else if (response != null && response.getJSONArray("data") != null) {
            // 处理直接返回数组的情况
            JSONArray voiceArray = response.getJSONArray("data");
            for (int i = 0; i < voiceArray.size(); i++) {
                JSONObject voiceObj = voiceArray.getJSONObject(i);
                String voiceName = voiceObj.getStr("voice_name");
                String voiceType = voiceObj.getStr("voice_type");
                voices.add(voiceType + " (" + voiceName + ")");
            }
        } else if (response != null) {
            // 处理响应本身就是数组的情况
            try {
                JSONArray voiceArray = JSONUtil.parseArray(response.toString());
                for (int i = 0; i < voiceArray.size(); i++) {
                    JSONObject voiceObj = voiceArray.getJSONObject(i);
                    String voiceName = voiceObj.getStr("voice_name");
                    String voiceType = voiceObj.getStr("voice_type");
                    voices.add(voiceType + " (" + voiceName + ")");
                }
            } catch (Exception e) {
                log.error("解析音色列表失败", e);
            }
        }
        
        log.info("获取到 {} 个音色", Optional.of(voices.size()));
        return voices;
    }

    @Override
    public InputStream textToSpeech(String text, String voice) {
        String ttsUrl = baseUrl.replace("/list", "/tts"); // 从list替换为tts
        
        // 构建请求体
        Map<String, Object> body = new HashMap<>();
        
        // 音频参数
        Map<String, Object> audio = new HashMap<>();
        audio.put("voice_type", voice);
        audio.put("encoding", "mp3");
        audio.put("speed_ratio", 1.0);
        body.put("audio", audio);
        
        // 请求参数
        Map<String, Object> request = new HashMap<>();
        request.put("text", text);
        body.put("request", request);
        
        // 添加调试日志，记录实际发送的请求参数
        log.info("TTS请求参数 - URL: {}, voice_type: {}, text: {}, 完整请求体: {}", 
                ttsUrl, voice, text, JSONUtil.toJsonStr(body));
        
        JSONObject response = postWithBearerToken(ttsUrl, body);
        
        if (response != null && response.containsKey("data")) {
            String base64Audio = response.getStr("data");
            if (base64Audio != null && !base64Audio.isEmpty()) {
                try {
                    byte[] audioBytes = Base64.decode(base64Audio);
                    log.info("TTS合成成功，音频大小: {} bytes", Optional.of(audioBytes.length));
                    return new ByteArrayInputStream(audioBytes);
                } catch (Exception e) {
                    log.error("Base64解码失败", e);
                    return null;
                }
            }
        }
        
        log.error("TTS合成失败");
        return null;
    }
    
    /**
     * TTS结果封装类
     */
    @Data
    public static class TtsResult {
        private boolean success;
        private String errorMessage;
        private JSONObject data;
        private byte[] audioData;
        
        public String getRequestId() {
            if (data != null) {
                return data.getStr("reqid");
            }
            return null;
        }
        
        public String getDuration() {
            if (data != null && data.containsKey("addition")) {
                JSONObject addition = data.getJSONObject("addition");
                return addition.getStr("duration");
            }
            return null;
        }
    }
}